package com.huonan.utils;

import cn.hutool.core.io.FileUtil;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.core.type.TypeReference;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 基于Jackson的JSON工具
 */

public class JacksonUtil {
    private static final Logger logger = LogManager.getLogger("JacksonUtil");

    private static ObjectMapper mapper = new ObjectMapper();

    static {
        // 将null值不序列化
        // objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);


        /* 将null值转换为空串 */
        mapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
            @Override
            public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers)
                    throws IOException, JsonProcessingException {
                gen.writeString("");
            }
        });
    }

    /**
     * 对象转换成JSON
     *
     * @param obj
     * @return
     */
    public static String toJson(Object obj) {
        StringWriter sw = new StringWriter();
        JsonGenerator gen = null;
        try {
            gen = new JsonFactory().createGenerator(sw);
            mapper.writeValue(gen, obj);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (gen != null) {
                try {
                    gen.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return sw.toString();
    }

    public static <T> T JsonToBean(String jsonStr, Class<T> objClass)
            throws JsonParseException, JsonMappingException, IOException {
        return mapper.readValue(jsonStr, objClass);
    }

    /**
     * 将 JSON 字符串转化为 Java 对象
     *
     * @param json
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T toObject(String json, Class<T> clazz) {
        T object = null;
        try {
            object = mapper.readValue(json, clazz);
        } catch (Exception e) {
            logger.error("JSON String Can't covert to Java Object!");
        }
        return object;
    }

    public static JsonNode stringToJson(String json) {

        ObjectMapper mapper = new ObjectMapper();
        JsonNode rootNode = null;
        try {
            rootNode = mapper.readTree(json);
        } catch (IOException e) {
            e.printStackTrace();
        }


        return rootNode;
    }

    /**
     * @return com.fasterxml.jackson.databind.JsonNode
     * @Description 解析
     * @Param [l]
     **/
    public static JsonNode parseJson(String l) {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode rootNode = null;
        try {
            return mapper.readTree(l);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @return java.lang.String
     * @Description 获取json中的字段
     * @Param [l, name]
     **/
    public static String getJsonValue(String l, String name) {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode rootNode = null;
        try {
            rootNode = mapper.readTree(l);
            assert rootNode != null;
            JsonNode idNode = rootNode.path(name);
            return mapper.writeValueAsString(idNode);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String convertMapToJson(Map<String, Object> map) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.writeValueAsString(map);
    }

    // 将JSON字符串转换为List
    public static List<String> stringListFromJson(String jsonArray) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.readValue(jsonArray, new TypeReference<List<String>>() {});
    }

    // 将List转换为JSON字符串
    public static String listToJson(List<String> list) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.writeValueAsString(list);
    }

    public static void main(String[] args) throws Exception {
        String json = "{\"username\":\"zhangsan\",\"性别\":\"男\",\"company\":{\"companyName\":\"中华\"," +
                "\"address\":\"北京\"},\"cars\":[\"奔驰\",\"宝马\"],\"logList\":[{\"id\":123,\"name\":\"abc\"},{\"id\":234," +
                "\"name\":\"efff\"}]}";
        //System.out.println(json);
        ObjectMapper mapper = new ObjectMapper();
        JsonNode rootNode = mapper.readTree(json);
        JsonNode company1 = rootNode.get("company");
        System.out.println(company1);
        JsonNode cars = rootNode.get("cars");
        ArrayNode  arrCars = (ArrayNode) cars;
        cars.forEach(System.out::println);
        JsonNode logList = rootNode.get("logList");
        ArrayNode  arrlogList = (ArrayNode ) logList;
        arrlogList.forEach(System.out::println);

        JsonNode usernameNode = rootNode.path("username");
        String username = mapper.writeValueAsString(usernameNode);
        System.out.println("==username==");
        System.out.println(username);

        //转换成类型,Map类型，同样Integer,String,List，也可以同样处理
        JsonNode companyNode = rootNode.path("company");
        String company = mapper.writeValueAsString(companyNode);
        Map<String, Object> companyMap = mapper.readValue(company, Map.class);
        System.out.println("==company==");
        System.out.println(companyMap);

        //转换成List<Log>，类型
        JsonNode logListNode = rootNode.path("logList");
        String logJson = mapper.writeValueAsString(logListNode);

        Map<String,Object> map = new HashMap<>();

        map.put("a1","bb");
        map.put("a2","");
        map.put("a3",new String[0]);
        map.put("a4",null);
        String s = toJson(map);

        System.out.println(s);
        FileUtil.writeUtf8String(s,"/Users/lxp/IdeaProjects/Study/MainTest/data/out2/jact.json");

    }
}
